package com.bootcamp.s2_0922.ds.Exercise._1004_Ex;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeMap;

public class Ex2_StudentTreeMap {

    public static void main(String[] args) throws IOException {
        TreeMap<Student, Integer> studentTree = new TreeMap<>(Ex2_StudentTreeMap::compareScore);
        // add students
        studentTree.put(new Student("lyi", 100, 110, 23), 1);
        studentTree.put(new Student("ler", 90, 110, 23), 2);
        studentTree.put(new Student("lsan", 100, 15, 123), 3);
        studentTree.put(new Student("lsi", 88, 90, 23), 4);
        studentTree.put(new Student("lwu", 105, 150, 13), 5);
        System.out.println(studentTree);

        // write to a file to store student info
        BufferedWriter writer = new BufferedWriter(new FileWriter("studentScoreList.txt"));
        // 获得从高到低排列的学生key
        Set<Student> stuInfos = studentTree.descendingKeySet();
        Iterator<Student> iterator = stuInfos.iterator();
        // 遍历存储到文件中
        while (iterator.hasNext()) {
            writer.write(iterator.next().toString());
            writer.newLine();
        }
        // close
        writer.close();
    }

    public static int compareScore(Student s1, Student s2) {
        double totalScore1 = s1.scoreChinese + s1.scoreEnglish + s1.scoreMath;
        double totalScore2 = s2.scoreChinese + s2.scoreEnglish + s2.scoreMath;
        int cmp = Double.compare(totalScore1, totalScore2);
        cmp = cmp != 0 ? cmp : Double.compare(s1.scoreChinese, s2.scoreChinese);
        cmp = cmp != 0 ? cmp : Double.compare(s1.scoreMath, s2.scoreMath);
        cmp = cmp != 0 ? cmp : Double.compare(s1.scoreEnglish, s2.scoreEnglish);
        cmp = cmp != 0 ? cmp : s1.name.compareTo(s2.name);
        return cmp;
    }
}

class Student {
    String name;
    double scoreChinese;
    double scoreMath;
    double scoreEnglish;

    public Student(String name, double scoreChinese, double scoreMath, double scoreEnglish) {
        this.name = name;
        this.scoreChinese = scoreChinese;
        this.scoreMath = scoreMath;
        this.scoreEnglish = scoreEnglish;
    }

    @Override
    public String toString() {
        final StringBuffer sb = new StringBuffer("Student{");
        sb.append("name='").append(name).append('\'');
        sb.append(", scoreChinese=").append(scoreChinese);
        sb.append(", scoreMath=").append(scoreMath);
        sb.append(", scoreEnglish=").append(scoreEnglish);
        sb.append('}');
        return sb.toString();
    }
}
